package utils;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/11 17:21
 * @Version 1.0
 */

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * Author: areful
 * Date: 2019/3/28
 */
public class CharByteKit {
    public static byte[] getBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        return bb.array();
    }

    public static char[] getChars(byte[] bytes) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes).flip();
        CharBuffer cb = cs.decode(bb);
        return cb.array();
    }

    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }

    public static char byteToChar(byte[] b) {
        int hi = (b[0] & 0xFF) << 8;
        int lo = b[1] & 0xFF;
        return (char) (hi | lo);
    }


    public static StringBuffer charsToStr(char[] b) {
        StringBuffer s = new StringBuffer();
        for (char c : b) {
            s.append(c);
        }
        return s;
    }

    public static StringBuffer bytesToStr(byte[] b) {
        return CharByteKit.charsToStr(CharByteKit.getChars(b));
    }

}
